import json

import requests

from utils.log_util import logger
from utils.read import base_data

api_root_url = base_data.read_ini()['host']['api_sit_url']


class RestClient:
    def __init__(self):
        self.api_root_url = api_root_url
        self.session = requests.session()

    def do_request(self, url, method, **kwargs):
        response = self.request(url, method, **kwargs).json()
        logger.info("返回接口内容>>>\n{}".format(json.dumps(response, ensure_ascii=False, indent=2)))
        return response

    def request(self, url, method, **kwargs):
        self.request_log(url, method, **kwargs)
        if method == 'GET':
            return self.session.get(self.api_root_url + url, **kwargs)
        if method == 'POST':
            return self.session.post(self.api_root_url + url, **kwargs)
        if method == 'DELETE':
            return self.session.delete(self.api_root_url + url, **kwargs)
        if method == 'PUT':
            return self.session.put(self.api_root_url + url, **kwargs)

    def request_log(self, url, method, **kwargs):
        data = kwargs.get('data')
        json_data = kwargs.get('json')
        params = kwargs.get('params')
        headers = kwargs.get('headers')

        logger.info(f'接口请求的地址是{self.api_root_url + url}')
        logger.info(f'接口请求的参数是{method}')

        if data is not None:
            logger.info(f'请求的data参数是{json.dumps(data, indent=2)}')
        if json_data is not None:
            logger.info(f'请求的json_data参数是{json.dumps(json_data, indent=2)}')
        if params is not None:
            logger.info(f'接口请求的params是{json.dumps(params, indent=2)}')
        if headers is not None:
            logger.info(f'接口请求的headers是{json.dumps(headers, indent=2)}')
